package com.luguangxing.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.luguangxing.entity.UserEntity;
import com.luguangxing.service.CommandResponseService;
import com.luguangxing.service.UploadedDataService;
import com.luguangxing.service.UserService;
import com.luguangxing.utils.MqttUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 小白一号
 * @date: 2022/12/12
 * @desc:
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class NbIotApi {
    @Resource
    private CommandResponseService commandResponseService;
    @Resource
    private UploadedDataService uploadedDataService;
    @Resource
    private UserService userService;

    /**
     * 消息流转发，在电信云平台的产品中添加设备数据变化通知的订阅
     *
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/getData")
    public UserEntity findUserByUserAccount(@RequestBody Map<String, Object> map) throws Exception {
        log.info("产品ID：" + map.get("productId"));
        log.info("设备ID：" + map.get("deviceId"));
        String imei = "";
        if (map.get("IMEI") != null) {
            imei = (String) map.get("IMEI");
        } else if (map.get("imei") != null) {
            imei = (String) map.get("imei");
        }
        log.info("设备IMEI：" + imei);
        log.info("传输协议：" + map.get("protocol"));
        log.info("消息体：" + JSON.toJSONString(map) + "\n\n");
        String messageType = (String) map.get("messageType");
        switch (messageType) {
            case "deviceOnlineOfflineReport":
                log.info("\n\n\n\n\n\n\n\n\\n\n\n\n\n\n---------------------------------设备上下线通知-----------------------------");
                break;
            case "dataReport":
                log.info("\n\n\n\n\n\n\n\n\\n\n\n\n\n\n---------------------------------设备数据变化通知-----------------------------");
                log.info("数据payload：" + map.get("payload"));
                saveUploadedData(JSON.toJSONString(map));
                String payload = map.get("payload").toString();
                if (payload.contains("card_id")) {
                    String cardId = payload.substring(9, 17);
                    log.info("cardId：" + cardId);
                    UserEntity userEntity = null;
                    userEntity = userService.findByUserCardId(cardId);
                    log.info("用户信息：");
                    if (userEntity != null) {
                        log.info(userEntity.toString());
                        //  开门
                        String body = "";
                        body = "{\"content\":{\"params\":{\"end\":\"AAA\"},\"serviceIdentifier\":\"is_allow\"},\"deviceId\":\"a0ff8dc91d0a489d8804ba67c0d00d80\",\"operator\":\"whiteone\",\"productId\":15459221,\"ttl\":0,\"level\":1}";
                        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                                .appKey("FDi2fk7VtN5").appSecret("5MBLbglA1B")
                                .build();

                        CreateCommandRequest request = new CreateCommandRequest();
                        // set your request params here
                        request.setParamMasterKey("c21072db7c9f468089b46641134e8601");    // single value
                        Map<String, Object> bodyMap = new HashMap();
                        // "{\"content\":{\"params\":{\"ledon\":0},\"serviceIdentifier\":\"led\"},\"deviceId\":\"a0ff8dc91d0a489d8804ba67c0d00d80\",\"operator\":\"whiteone\",\"productId\":15459221,\"ttl\":0,\"level\":1}"
                        request.setBody(body.getBytes());    //具体格式见前面请求body说明
                        System.out.println("Here" + client.CreateCommand(request));
                        // more requests

                        client.shutdown();
                    } else {
                        MqttUtil.publish("toAndroidCardBinding/" + imei, JSON.toJSONString(map));
                        log.info("用户不存在");
                        String body = "";
                        body = "{\"content\":{\"params\":{\"end\":\"BBB\"},\"serviceIdentifier\":\"is_allow\"},\"deviceId\":\"a0ff8dc91d0a489d8804ba67c0d00d80\",\"operator\":\"whiteone\",\"productId\":15459221,\"ttl\":0,\"level\":1}";
                        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                                .appKey("FDi2fk7VtN5").appSecret("5MBLbglA1B")
                                .build();

                        CreateCommandRequest request = new CreateCommandRequest();
                        // set your request params here
                        request.setParamMasterKey("c21072db7c9f468089b46641134e8601");    // single value
                        Map<String, Object> bodyMap = new HashMap();
                        // "{\"content\":{\"params\":{\"ledon\":0},\"serviceIdentifier\":\"led\"},\"deviceId\":\"a0ff8dc91d0a489d8804ba67c0d00d80\",\"operator\":\"whiteone\",\"productId\":15459221,\"ttl\":0,\"level\":1}"
                        request.setBody(body.getBytes());    //具体格式见前面请求body说明
                        System.out.println("Here" + client.CreateCommand(request));
                        // more requests

                        client.shutdown();
                    }
                } else {
                    MqttUtil.publish("toAndroid/" + imei, JSON.toJSONString(map));
                }
                break;
            case "commandResponse":
                log.info("\n\n\n\n\n\n\n\n\\n\n\n\n\n\n---------------------------------设备指令响应通知-----------------------------");
                commandSave(JSON.toJSONString(map));
                break;
        }
        return null;
    }

    private boolean commandSave(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        jsonObject.put("resultDetail", JSON.parseObject(jsonObject.get("result").toString()).get("resultDetail"));
        jsonObject.put("resultCode", JSON.parseObject(jsonObject.get("result").toString()).get("resultCode"));
        jsonObject.remove("result");
        Map<String, Object> map = JSONObject.parseObject(jsonObject.toJSONString(), HashMap.class);
        if (commandResponseService.saveCommandResponse(map) > 0) {
            log.info("保存成功");
        } else {
            log.info("保存失败");
        }
        return true;
    }

    private boolean saveUploadedData(String json) {
        Map<String, Object> map = JSONObject.parseObject(json, HashMap.class);
        map.put("payload", map.get("payload").toString());
        if (uploadedDataService.saveUploadedData(map) > 0) {
            log.info("保存成功");
        } else {
            log.info("保存失败");
        }
        return true;
    }
}
